package com.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.domain.ResponseResult;
import com.peng.domain.entity.User;
import com.peng.domain.entity.UserRole;
import com.peng.domain.vo.PageVo;
import com.peng.domain.vo.UserInfoVo;
import com.peng.enums.AppHttpCodeEnum;
import com.peng.exception.SystemException;
import com.peng.mapper.UserMapper;
import com.peng.service.RoleService;
import com.peng.service.UserRoleService;
import com.peng.service.UserService;
import com.peng.utils.BeanCopyUtils;
import com.peng.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2022-10-04 16:53:27
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public ResponseResult userInfo() {
        // 获取当前用户id
        Long userId = SecurityUtils.getUserId();
        // 根据用户id查询用户信息
        User user = getById(userId);
        // 封装成userInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(User user) {
        // 对数据进行非空判断
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        // 对数据进行是否重复的判断
        if (userNameExist(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (nickNameExist(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if (EmailExist(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        // 对密码进行加密处理
        String encodePassword = passwordEncoder.encode(user.getPassword());
        // 存入数据库
        user.setPassword(encodePassword);
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public PageVo getPageList(Integer pageNum, Integer pageSize, User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(user.getUserName()), User::getUserName, user.getUserName());
        queryWrapper.like(StringUtils.hasText(user.getPhonenumber()), User::getPhonenumber, user.getPhonenumber());
        queryWrapper.like(StringUtils.hasText(user.getStatus()), User::getStatus, user.getStatus());

        Page<User> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page, queryWrapper);

        List<User> users = page.getRecords();

        PageVo pageVo = new PageVo();
        pageVo.setRows(users);
        pageVo.setTotal(page.getTotal());
        return pageVo;
    }

    @Override
    @Transactional
    public ResponseResult addUser(User user) {
        // 对数据进行非空判断
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        // 对数据进行是否重复的判断
        if (userNameExist(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (phoneNumber(user.getPhonenumber())) {
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        if (EmailExist(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);

        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            List<UserRole> userRoles = Arrays.stream(user.getRoleIds())
                    .map(new Function<Long, UserRole>() {
                        @Override
                        public UserRole apply(Long roleId) {
                            return new UserRole(user.getId(), roleId);
                        }
                    }).collect(Collectors.toList());
            userRoleService.saveBatch(userRoles);
        }
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public void edit(User user) {
        // 删除用户与角色关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(queryWrapper);

        // 新增用户与角色管理
        List<UserRole> userRoles = Arrays.stream(user.getRoleIds())
                .map(new Function<Long, UserRole>() {
                    @Override
                    public UserRole apply(Long roleId) {
                        return new UserRole(user.getId(), roleId);
                    }
                }).collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        // 更新用户信息
        updateById(user);
    }

    private boolean EmailExist(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getEmail, email);
        int count = count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getNickName, nickName);
        int count = count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    private boolean phoneNumber(String phoneNumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getPhonenumber, phoneNumber);
        int count = count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserName, userName);
        int count = count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
}

